﻿using System;
using System.Linq;
using System.Web.Http;
using FellowshipOne.API;
using FellowshipOne.API.Base;
using FellowshipOne.API.Events.Model;
using FellowshipOne.API.Events.QueryObject;
using FellowshipOne.API.Groups.Model;
using FellowshipOne.API.Groups.QueryObject;
using MasVida.WebApi.Controllers.Interfaces;
using MasVida.WebApi.Models.DataObject;
using MasVida.WebApi.Models.Requests;
using MasVida.WebApi.Models.Responses;
using Newtonsoft.Json.Linq;
using RestSharp.Extensions;

namespace MasVida.WebApi.Controllers
{
    public class GroupController : ApiBaseController
    {
        
        public GroupController()
        {
            
        }

        public GroupController(IRestClient restClient)
        {
            RestClient = restClient;
        }

        [HttpPost]
        public GroupsResponse GetGroupsForUser([FromBody]JObject jobject)
        {
            GroupRequest groupRequest = GetGroupRequestFromJObject(jobject);
                
            GroupsResponse response = new GroupsResponse();
            try
            {
                IRestClient restClient = GetRestClient(groupRequest.AccessTicket);
                MemberQO query = new MemberQO { PersonId = groupRequest.PersonId };
                MemberCollection memberCollection = restClient.GroupsRealm.Member.Search<MemberCollection>(query);
                response.Groups = memberCollection
                    .Where(m => m.MemberType.ID == 1)
                    .Select(m => new GroupDO()
                {
                    GroupId = m.Group.ID ?? 0,
                    Name = m.Group.Name
                });
            }
            catch (Exception ex)
            {
                response.ErrorMessage = ex.Message;
            }
            return response;

        }

        private GroupRequest GetGroupRequestFromJObject(JObject jobject)
        {
            return new GroupRequest()
            {
                ApiKey = jobject["ApiKey"]?.Value<string>(),
                PersonId = jobject["PersonId"]?.Value<int>() ?? 0,
                AccessTicket = jobject["AccessTicket"]?.ToObject<F1OAuthTicket>()
            };
        }

        
    }
}